package com.ruoyi.checkingin.controller;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.TimeUnit;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.checkingin.service.IEChecksService;
import com.ruoyi.checkingin.service.IERpRecordService;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.e_checkingin.EChecks;
import com.ruoyi.common.core.domain.e_checkingin.ERpRecord;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.core.domain.e_checkingin.ECheckTime;
import com.ruoyi.checkingin.service.IECheckTimeService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

import static com.ruoyi.common.constant.PersonConstants.Day_count;
import static com.ruoyi.common.constant.PersonConstants.First_checkin;
import static com.ruoyi.common.utils.DateUtils.YYYY_MM_DD_HH_MM_SS;

/**
 * 考勤记录Controller
 * 
 * @author JYW
 * @date 2024-01-30
 */
@RestController
@RequestMapping("/checkingin/time")
public class ECheckTimeController extends BaseController
{
    @Autowired
    private IECheckTimeService eCheckTimeService;

    @Autowired
    private EChecksController eChecksController;

    @Autowired
    private IERpRecordService rpRecordService;

    @Autowired
    private RedisCache redisCache;

    /**
     * 查询考勤记录列表
     */
    @PreAuthorize("@ss.hasPermi('checkingin:time:list')")
    @GetMapping("/list")
    public TableDataInfo list(ECheckTime eCheckTime)
    {
        startPage();
        List<ECheckTime> list = eCheckTimeService.selectECheckTimeList(eCheckTime);
        return getDataTable(list);
    }

    /**
     * 查询个人考勤记录列表
     */
//    @PreAuthorize("@ss.hasPermi('checkingin:time:list')")
    @GetMapping("/listbyMe")
    public AjaxResult listbyMe(@RequestParam Object time)
    {
        startPage();
        ECheckTime eCheckTime = new ECheckTime();
        eCheckTime.setuId(SecurityUtils.getUserId());
        if (time == null || time.equals(" ")){
            eCheckTime.setCreateTime(DateUtils.dateTime("yyyy-MM-dd",DateUtils.dateTime(new Date())));
        }else {
            eCheckTime.setCreateTime(DateUtils.dateTime("yyyy-MM-dd", (String) time));
        }

        List<ECheckTime> list = eCheckTimeService.selectECheckTimeList(eCheckTime);

        Map<String,Object> map = new HashMap<>();

        if (list.isEmpty()){
            map.put("checkin",new ECheckTime());
            map.put("interval",0);
            map.put("frequency",0);
            return AjaxResult.success(map);
        }
        map.put("checkin",list.get(0));
        map.put("interval",0);
        map.put("frequency",1);
        if (list.get(0).getSignInTime() !=null && list.get(0).getSignOutTime() != null){
            Long time2  =(list.get(0).getSignOutTime().getTime()-list.get(0).getSignInTime().getTime())/1000/60/60;
            map.put("interval",time2);
            map.put("frequency",2);
        }
        return AjaxResult.success(map);
    }


    /**
     * 查询个人考勤记录列表
     */
//    @PreAuthorize("@ss.hasPermi('checkingin:time:list')")
    @GetMapping("/listbyUId")
    public TableDataInfo listbyUId()
    {
        startPage();
        ECheckTime eCheckTime = new ECheckTime();
        eCheckTime.setuId(SecurityUtils.getUserId());
        List<ECheckTime> list = eCheckTimeService.selectECheckTimeList(eCheckTime);
        List<Map<String,Object>> mapList = new ArrayList<>();
        list.forEach(eCheckTime1 -> {
            String[] s1 = DateUtils.parseDateToStr(YYYY_MM_DD_HH_MM_SS, eCheckTime1.getSignInTime()).split(" ");
            String[] s2 = DateUtils.parseDateToStr(YYYY_MM_DD_HH_MM_SS, eCheckTime1.getSignOutTime()).split(" ");
            Map<String,Object> map = new HashMap<>();
            map.put("day",s1[0]);
            map.put("signIn",s1[1]);
            map.put("signOut",s2[1]);
            map.put("checkTime",eCheckTime1);
            mapList.add(map);
        });
        return getDataTable(mapList);
    }

    /**
     * 导出考勤记录列表
     */
    @PreAuthorize("@ss.hasPermi('checkingin:time:export')")
    @Log(title = "考勤记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ECheckTime eCheckTime)
    {
        List<ECheckTime> list = eCheckTimeService.selectECheckTimeList(eCheckTime);
        ExcelUtil<ECheckTime> util = new ExcelUtil<ECheckTime>(ECheckTime.class);
        util.exportExcel(response, list, "考勤记录数据");
    }

    /**
     * 获取考勤记录详细信息
     */
//    @PreAuthorize("@ss.hasPermi('checkingin:time:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(eCheckTimeService.selectECheckTimeById(id));
    }

    /**
     * 新增考勤记录
     */
//    @PreAuthorize("@ss.hasPermi('checkingin:time:add')")
    @Log(title = "考勤记录", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ECheckTime eCheckTime)
    {
        //1.获取用户id、当前时间
        Long userId = SecurityUtils.getUserId();
        //3.设置属性
        eCheckTime.setuId(userId);
        //2。对当前时间通过考勤信息表进行判断，属于什么打卡状态
        List<EChecks> eChecks = (List<EChecks>) eChecksController.list(new EChecks()).getRows();
       //判断是否已经签到，如果已经签到，则改为签退
        Integer i = this.sentenceCheck(eCheckTime, eChecks);
        return toAjax(i);
    }

    public Integer sentenceCheck(ECheckTime eCheckTime,List<EChecks> eChecks){
        int i = 0;
        Date date = new Date();
        if (redisCache.getCacheObject(First_checkin+SecurityUtils.getUserId())==null){
            eCheckTime.setSignInTime(date);
            for (EChecks eChecks1 :eChecks){
                if (DateUtils.timeInScope(date,eChecks1.getTimeScope())){
                    eCheckTime.setSignInStatus(eChecks1.getStage());
                    break;
                }
            }
            i = eCheckTimeService.insertECheckTime(eCheckTime);
            //设置过期时间为本日的剩余时间
            redisCache.setCacheObject(First_checkin+SecurityUtils.getUserId(),eCheckTime.getId(), (int) DateUtils.remainTime(date), TimeUnit.MINUTES);
        }else {
            //从redis获取该数据，并设置签退时间
            eCheckTime.setId(redisCache.getCacheObject(First_checkin+SecurityUtils.getUserId()));
            eCheckTime.setSignOutTime(date);
            for (EChecks eChecks1 :eChecks){
                if (DateUtils.timeInScope(date,eChecks1.getTimeScope())){
                    eCheckTime.setSignOutStatus(eChecks1.getStage());
                    break;
                }
            }
            i = eCheckTimeService.updateECheckTime(eCheckTime);
        }
        return i;
    }

    /**
     * 修改考勤记录
     */
//    @PreAuthorize("@ss.hasPermi('checkingin:time:edit')")
    @Log(title = "考勤记录", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ECheckTime eCheckTime)
    {
        return toAjax(eCheckTimeService.updateECheckTime(eCheckTime));
    }

    /**
     * 删除考勤记录
     */
//    @PreAuthorize("@ss.hasPermi('checkingin:time:remove')")
    @Log(title = "考勤记录", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(eCheckTimeService.deleteECheckTimeByIds(ids));
    }

    /*
    * 首页员工状态查看
    * */
    @GetMapping("/homePage")
    public AjaxResult homePage(){
        Map<String, Object> map = eCheckTimeService.homePageUser();
        return AjaxResult.success(map);
    }
}
